# download_oss_files.py

import os
import oss2
from config import ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET
from config import OSS_ENDPOINT, OSS_BUCKET_NAME, OSS_REMOTE_FOLDER, LOCAL_DIR


# 初始化 OSS bucket 对象
auth = oss2.Auth(ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)

# 确保本地目录存在
os.makedirs(LOCAL_DIR, exist_ok=True)


# 分页列出所有以 remote_folder 开头的对象
def download_folder(bucket, remote_folder, local_dir):
    for obj in oss2.ObjectIterator(bucket, prefix=remote_folder):
        remote_path = obj.key
        local_path = os.path.join(local_dir, os.path.relpath(remote_path, remote_folder))

        # 如果是目录结构，创建对应子目录
        local_folder = os.path.dirname(local_path)
        os.makedirs(local_folder, exist_ok=True)

        # 下载文件
        if not remote_path.endswith('/'):  # 排除纯目录对象（有些服务会生成虚拟目录项）
            print(f"Downloading {remote_path} to {local_path}")
            bucket.get_object_to_file(remote_path, local_path)


# 执行下载
download_folder(bucket, OSS_REMOTE_FOLDER, LOCAL_DIR)

print("文件夹下载完成")